<?php

namespace App\Admin\Controllers;

use App\Models\Department;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Tree;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DepartmentController extends BaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '部门管理';


    public function index(Content $content)
    {

        $employees = new Department();
        $employees->query()->withCount('employees');

        return $content->header('部门管理')
            ->row(function ($row) {
                $row->column(10, $this->treeView()->render());
            });
    }


    protected function treeView()
    {
        $tree = new Tree(new Department());

        $tree->query(function ($model){
            return $model->with('employees');
        });
        $users = User::Users();
        $tree->branch(function ($branch) use ($users) {

            $ids = self::SumEmployees([$branch['id']]);
            User::query()->whereIn('department_id',$ids)->count();
            $count = User::query()->whereIn('department_id',$ids)->count();// empty($branch['employees']) ? 0 : count($branch['employees']);
            if($branch['leader'] == 1){
                $leader = '';
            }else{
                $leader = empty($branch['leader']) ? '' : $users[$branch['leader']];
            }
            $employees = empty($branch['employees']) ? '' : join(', ',collect($branch['employees'])->pluck('name')->toArray());
            $payload = "&nbsp;<strong>{$branch['title']}  &nbsp;&nbsp;( {$count} 人)  </strong>";
            $payload .= "<small style='color: grey'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;主管： $leader</small>";
            $payload .= "<small style='color: grey'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;组员： $employees</small>";
            return $payload;
        });
        return $tree;
    }

    /**
     * 获取当前部门下的所有部门ID
     * @param array $ids
     * @return array|\Illuminate\Support\Collection
     */
    public function SumEmployees($ids=[])
    {
        $query = Department::query()->whereIn('parent_id',$ids);
        if($query->count() > 0){
            $ids = $query->pluck('id');
            return $ids->concat(self::SumEmployees($ids));
        }
        return $ids;
    }

    public function create(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body($this->form());
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Department::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    protected function form()
    {
        $form = new Form(new Department());
        $deps = Department::allDepartment();
        $deps[0] = '根目录';
        ksort($deps);
        $users = User::Users();
        $form->hidden('id', __('ID'));
        $form->text('title','部门名称')->required();
        $form->select('parent_id','上级部门')->options($deps);
        $form->select('leader','部门领导')->options($users)->required();
//        $form->multipleSelect('employee','部门成员')->options(User::Users());

        $form->saved(function (Form $form){
            // 刷新leader信息
            User::query()->update(['is_leader'=>2]);
            Department::query()->each(function ($item){
                User::query()->where('id',$item->leader)->update(['is_leader'=>1,'department_id'=>$item->id]);
            });
            // 更新 部门 level
            Department::updateLevel();
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
            $tools->disableList();
        });
        $form->disableEditingCheck();
        $form->disableCreatingCheck();
        $form->disableViewCheck();

        $form->saved(function (Form $form){
            if($form->isCreating()){
                admin_toastr('添加成功','success');
            }
            if($form->isEditing()){
                admin_toastr('修改成功','success');
            }
            return redirect('/admin/users');
        });

        return $form;
    }

    public function destroy($id)
    {
        try{
            Department::query()->where('id',$id)->delete();
            $response = [
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ];
        }catch (\Exception $exception){
            $response = [
                'status'  => false,
                'message' => $exception->getMessage() ?: trans('admin.delete_failed'),
            ];
        }
        return response()->json($response);
    }


    public function getDepartment(Request $request)
    {
        $pid = $request->get('q');
        dd($pid);
        return Department::query()->where('parent_id',$pid)->get(['id', DB::raw('title as text')]);
    }

}
